package busi

import (
	"errors"
	"fmt"
	htbsc "gitee.com/hangzhou_huitian/ht-basic/basic"
	"gorm.io/gorm"
	"hisim/global"
	"net/http"
	"slices"
	"strconv"
	"strings"
	"time"
)

func OrderIn() {
	p := findPatient("in")
	if p == nil {
		return
	}

	fo := findNewOrder(p)
	if fo == nil {
		return
	}

	cf := global.Conf
	var emp Response
	if err := global.HttpRequest[Response](cf.CollectorAddr+"/order/in", http.MethodPost, nil, fo, &emp); err != nil {
		fmt.Println(err.Error())
		return
	} else {
		if emp.Status != 200 {
			fmt.Println("order in error:", emp.Text)
			return
		}
		os := &OrderScene{}
		if err = db.Table("order_scene").Where("visit_no=?", p.VisitNo).Scan(&os).Error; err != nil {
			fmt.Println("order_scene" + err.Error())
			return
		} else {
			os.OrderSeq = fo.Seq
			if os.Id == 0 {
				os.VisitNo = p.VisitNo
				os.Scene = fo.Scene
				if err = db.Table("order_scene").Save(&os).Error; err != nil {
					fmt.Println("order_scene" + err.Error())
					return
				}
			} else if err = db.Table("order_scene").Where("id=?", os.Id).Update("order_seq", os.OrderSeq).Error; err != nil {
				fmt.Println("order_scene" + err.Error())
			}
			fmt.Println("add order:", os.VisitNo, fo.Seq)
		}
	}
}

func OrderUpdate() {
	var tryTimes = 0
	var p *Patient
	os := &OrderScene{}
	for {
		if tryTimes > 3 {
			return
		}
		tryTimes++

		p = findPatient("in")
		if p == nil {
			return
		}

		if err := db.Table("order_scene").Where("visit_no=?", p.VisitNo).First(&os).Error; err != nil && !errors.Is(gorm.ErrRecordNotFound, err) {
			fmt.Println("order_scene:" + err.Error())
		} else if errors.Is(gorm.ErrRecordNotFound, err) {
			return
		}
		if os.OrderSeq < 5 {
			continue
		}
		break
	}

	updatedOrders := strings.Split(os.UpdatedOrders, ",")

	index := 0
	findCount := 0
	for {
		if findCount > 6 {
			return
		}
		findCount++
		if os.OrderSeq >= 2 {
			index = ra.Intn(os.Scene + 1)
		}
		if slices.Contains(updatedOrders, strconv.Itoa(index)) { //找一个没更新过的医嘱
			continue
		}
		break
	}

	cf := global.Conf
	var emp Response
	if err := global.HttpRequest[Response](cf.CollectorAddr+"/order/update",
		http.MethodGet,
		map[string]string{"visitNo": p.VisitNo, "seq": strconv.Itoa(index)}, nil, &emp); err != nil {
		fmt.Println(err.Error())
		return
	} else if emp.Status != 200 {
		fmt.Println("order update error:", emp.Text)
		return
	} else {
		os = &OrderScene{}
		os.UpdatedOrders += strconv.Itoa(index)
		if err = db.Table("order_scene").Where("visit_no=?", p.VisitNo).Update("updated_orders", os.UpdatedOrders).Error; err != nil {
			fmt.Println("order_scene" + err.Error())
		}
	}
}

func findNewOrder(p *Patient) *Order {
	os := &OrderScene{}
	if err := db.Table("order_scene").Where("visit_no=?", p.VisitNo).Scan(&os).Error; err != nil {
		fmt.Println("order_scene" + err.Error())
		return nil
	}

	var scene = 1
	var step = 0
	visitNo := p.VisitNo
	if os.Id == 0 { //初次下发医嘱
		step = 0
	} else {
		step = os.OrderSeq + 1
	}

	o := findOrderByScene(scene, step)
	if o == nil {
		return nil
	}

	tm := htbsc.HtTime(time.Now())
	o.ID = 0
	o.VisitNo = visitNo
	o.AreaCode = p.Area
	o.OrderId = visitNo + "||" + fmt.Sprintf("%d", step+1)
	o.OrderStatus = htbsc.OsValid
	o.UpdateTime = tm
	o.EnterTime = tm
	o.ExecTime = tm
	o.StopTime = tm
	o.Seq = step
	return o
}

func findOrderByScene(scene int, step int) *Order {
	var oList = loadOrderByScene(scene)
	if step >= len(oList) {
		return nil
	} else {
		return oList[step]
	}
}

func loadOrderByScene(scene int) []*Order {
	var oList []*Order
	if err := db.Table("orders").Where("scene=?", scene).Order("enter_time,id").Scan(&oList).Error; err != nil {
		fmt.Println(err.Error())
		return nil
	} else {
		return oList
	}
}
